<?php

App::uses('CrudController', 'Controller');
App::uses('SimplePasswordHasher', 'Controller/Component/Auth');
App::uses('User', 'Model');

class UsersController extends CrudController
{
    public $_model = 'User';

    public function admin() {
        $this->request->allowMethod('get');
        $myCategory = $this->Auth->user('category_id');
        $this->loadModel('Category');
        $this->loadModel('Area');
        $this->loadModel('Team');
        $categories = Category::getCategories($myCategory);
        $types = User::getPublicStatus($myCategory);
        $appBosch = new stdClass();
        $appBosch->categories = $categories;
        $appBosch->myCategory = $myCategory;
        $appBosch->types = $types;
        $appBosch->teams = $this->Team->getTeamsByUserArea($this->Auth->user('id'));
        $appBosch->asociadoCategoryId = Category::ASOCIADO;
        $this->set('appBosch', $appBosch);
        $this->set('title', __('Usuarios'));
        $this->set('description', __('Administración'));
    }

    public function changePassForm()
    {
        $this->set('title', __('Cambiar contraseña'));
        $this->set('description', __('Modifica tu contraseña'));
    }

    public function changePass()
    {
        $data = $this->request->data;
        $passwordHasher = new SimplePasswordHasher();
        $pass = $passwordHasher->hash($data['pass']);
        $userSesion = $this->Auth->user();
        $userId = $userSesion['id'];
        $userBD = $this->User->findById($userId);
        $passBD = $userBD['User']['p4ss'];
        $success = true;
        $msg = __('La constraseña ha sido cambiada con exito.');
        if ($passBD == $pass) {
            if ($data['newPass1'] == $data['newPass2']) {
                if (mb_strlen($data['newPass1']) >= 6 && mb_strlen($data['newPass1']) <= 10) {
                    $newPass = $data['newPass1'];
                    $this->User->changePass($userId, $newPass);
                } else {
                    $success = false;
                    $msg = __('La contraseña debe de tener mínimo 6 caracteres y máximo 10');
                }
            } else {
                $success = false;
                $msg = __('La nueva contraseña y su confirmacion no coinciden.');
            }
        } else {
            $success = false;
            $msg = __('Tu contraseña no es correcta.');
        }
        $this->set('title', __('Cambiar contraseña'));
        $this->set('description', __('Modifica tu contraseña'));
        $this->set('success', $success);
        $this->set('msg', $msg);
    }

    public function resetPass($id)
    {
        $this->request->allowMethod('get');
        $success = false;
        if ($this->request->is('ajax') === true) {
            $this->User->id = $id;
            $user = $this->User->read();
            if (isset($user['User']) === true) {
                $user['User']['p4ss'] = 't3mp0r4l';
                $usr = $this->User->save($user['User']);
                $success = $usr !== false;
            }
        }
        $this->set(array('success' => $success, '_serialize' => 'success'));
        $this->viewClass = 'Json';
    }

    /** obtenemos los permisos de un usuario */
    public function getPermissions($userId)
    {
        $permissions = 0;
        if ($this->request->is('ajax') === true && $this->request->allowMethod('get') === true) {
            $this->User->id = $userId;
            $user = $this->User->read();
            if (isset($user['User']) === true) {
                $permissions = $user['User']['permissions'];
            }
        }
        $objPermissions = new CertificationPermissions($permissions);
        $this->set(array('permissions' => $objPermissions->toArray(), '_serialize' => 'permissions'));
        $this->viewClass = 'Json';
    }

    public function savePermissions()
    {
        $success = false;
        if ($this->request->is('ajax') === true && $this->request->allowMethod('get') === true) {
            $params = $this->request->query;
            $uId = $params['uId'];
            $c = $params['c'];
            $r = $params['r'];
            $u = $params['u'];
            $d = $params['d'];
            $end = $params['end'];
            $life = $params['life'];
            $data = array(
                'id' => $uId,
                'permissions' => CertificationPermissions::toBin($c, $r, $u, $d, $end, $life),
            );
            $this->User->save($data);
            $success = true;
        }
        $this->set(array('success' => $success, '_serialize' => 'success'));
        $this->viewClass = 'Json';
    }

    public function getSessionPermissions()
    {
        $permissions = 0;
        if ($this->request->is('ajax') === true && $this->request->allowMethod('get') === true) {
            $this->User->id = $this->Auth->user('id');
            $user = $this->User->read();
            if (isset($user['User']) === true) {
                $permissions = $user['User']['permissions'];
            }
        }
        $objPermissions = new CertificationPermissions($permissions);
        $this->set(array('permissions' => $objPermissions->toArray(), '_serialize' => 'permissions'));
        $this->viewClass = 'Json';
    }

    protected function getRecords($param = null)
    {
        $m = $this->_model;
        $records = $this->$m->getEnabledShortDesciption($param);
        array_walk($records, function (&$r) {
            $r['sup'] = $r['sup'] == '1';
            $r['ie'] = $r['ie'] == '1';
        });
        return $records;
    }

    protected function c($model)
    {
        $date = DateTime::createFromFormat('Y-m-d\TH:i:s.u\Z', trim($model->ad));
        $strDate = $date->format('Y-m-d');
        return array(
            'nomina' => $model->nom === null ? null : mb_strtoupper(trim($model->nom)),
            'curp' => $model->c === null ? null : mb_strtoupper(trim($model->c)),
            'us3r' => $model->nom === null ? $this->getUs3r($model->n, $model->ln1, $model->ln2) : trim($model->nom),
            'p4ss' => $model->c === null ? 't3mp0r4l' : mb_strtoupper(trim($model->c)),
            'full_name' => mb_strtoupper(trim($model->n) . ' ' . trim($model->ln1) . ' ' . trim($model->ln2)),
            'admission_date' => $strDate,
            'name' => mb_strtoupper(trim($model->n)),
            'last_name_1' => mb_strtoupper(trim($model->ln1)),
            'last_name_2' => mb_strtoupper(trim($model->ln2)),
            'category_id' => trim($model->cId),
            'support' => (int)($model->sup === true ? User::SUPPORT_ON : User::SUPPORT_OFF),
            'is_external' => (int)($model->ie === true ? User::EXTERNAL_ON : User::EXTERNAL_OFF),
            'status' => trim($model->status),
            'team' => $model->team ? $model->team->value : ''
        );
    }

    protected function beforeCreate(&$newRecord)
    {
        $us1 = $this->User->getByNomina($newRecord['nomina']);
        $us2 = $this->User->getByCURP($newRecord['curp']);
        $resp = new stdClass();
        if (count($us1) > 0) {
            $resp->error = true;
            $resp->message = __('Ya existe un usuario con este numero de nómina');
        } elseif (count($us2) > 0) {
            $resp->error = true;
            $resp->message = __('Ya existe un usuario con esta CURP');
        } else {
            $resp = true;
        }

        return $resp;
    }

    protected function afterCreate(&$newRecord)
    {
        if ($newRecord['category_id'] == Category::ASOCIADO) {
            $this->loadModel('TeamUser');
            $tu = array(
                'team_id' => $newRecord['team'],
                'user_id' => $newRecord['id'],
            );
            $this->TeamUser->save($tu);
        }
    }

    private function getUs3r($name, $lastName1, $lastName2)
    {
        return strtolower(str_replace(' ', '', trim($name)) .
            str_replace(' ', '', trim($lastName1)) .
            str_replace(' ', '', trim($lastName2)));
    }

    protected function resultCreate($model)
    {
        if (is_array($model)) {
            return array(
                'id' => $model['id'],
                'nom' => $model['nomina'],
                'c' => $model['curp'],
                'cId' => $model['category_id'],
                'fn' => $model['full_name'],
                'n' => $model['name'],
                'ln1' => $model['last_name_1'],
                'ln2' => $model['last_name_2'],
                'status' => $model['status'],
                'ad' => $model['admission_date'],
                'sup' => $model['support'],
                'ie' => $model['is_external'],
            );
        } else {
            return $model;
        }
    }

    protected function u($model)
    {
        $date = DateTime::createFromFormat('Y-m-d\TH:i:s.u\Z', trim($model->ad));
        $strDate = $date->format('Y-m-d');
        return array(
            'nomina' => $model->nom === null ? null : mb_strtoupper(trim($model->nom)),
            'us3r' => $model->nom,
            'curp' => $model->c === null ? null : mb_strtoupper(trim($model->c)),
            'full_name' => mb_strtoupper(trim($model->n) . ' ' . trim($model->ln1) . ' ' . trim($model->ln2)),
            'admission_date' => $strDate,
            'name' => trim($model->n),
            'last_name_1' => mb_strtoupper(trim($model->ln1)),
            'last_name_2' => mb_strtoupper(trim($model->ln2)),
            'category_id' => trim($model->cId),
            'support' => (int)($model->sup === true ? User::SUPPORT_ON : User::SUPPORT_OFF),
            'is_external' => (int)($model->ie === true ? User::EXTERNAL_ON : User::EXTERNAL_OFF),
            'status' => trim($model->status)
        );
    }

    protected function resultUpdate($id, $result)
    {
        return array(
            'id' => $id,
            'nom' => $result['nomina'],
            'c' => $result['curp'],
            'cId' => $result['category_id'],
            'fn' => $result['full_name'],
            'n' => $result['name'],
            'ln1' => $result['last_name_1'],
            'ln2' => $result['last_name_2'],
            'status' => $result['status'],
            'ad' => $result['admission_date'],
            'sup' => $result['support'],
            'ie' => $result['is_external'],
        );
    }

    public function getForManagers() {
        $m = $this->_model;
        $records = $this->$m->getEnabledForManagers();
        $this->set(array('records' => $records, '_serialize' => 'records'));
        $this->viewClass = 'Json';
    }

    public function usersPhotos() {
        $appBosch = new stdClass();
        $this->set('appBosch', $appBosch);
        $this->set('title', __('Fotos'));
        $this->set('description', __('Subir fotos de los asociados'));
    }

    public function uploadPhotos() {
        $response = new stdClass();
        if (isset($_FILES['files'])) {
            try {
                $pathT = TMP . 'img' . DS . 'tmp';
                $pathN = TMP . 'img' . DS . 'workers';
                $pathM = TMP . 'img' . DS . 'workers-mini';
                if (!file_exists($pathT)) {
                    mkdir($pathT, 0777, true);
                }
                if (!file_exists($pathN)) {
                    mkdir($pathN, 0777, true);
                }
                if (!file_exists($pathM)) {
                    mkdir($pathM, 0777, true);
                }
                $file = $_FILES['files'];
                $filename = $pathT . DS . $file['name'];
                move_uploaded_file($file['tmp_name'], $filename);
                list($ancho, $alto) = getimagesize($filename);
                $imgN = imagecreatetruecolor(100, 100);
                $imgM = imagecreatetruecolor(30, 30);
                $origen = $this->imagecreatefromtype($file['type'], $filename);
                imagecopyresized($imgN, $origen, 0, 0, 0, 0, 100, 100, $ancho, $alto);
                imagecopyresized($imgM, $origen, 0, 0, 0, 0, 30, 30, $ancho, $alto);
                $fn = explode('.', $file['name']);
                imagejpeg($imgN, $pathN . DS . $fn[0] . '.jpg');
                imagejpeg($imgM, $pathM . DS . $fn[0] . '.jpg');
                unlink($filename);
                $response->error = false;
            } catch (Exception $ex) {
                $response->error = true;
            }
        } else {
            $response->error = true;
        }
        $this->set(array('records' => $response, '_serialize' => 'records'));
        $this->viewClass = 'Json';
    }

    private function imagecreatefromtype($imageType, $filename) {
        switch ($imageType) {
            case 'image/jpeg':
                return imagecreatefromjpeg($filename);
                break;
            case 'image/png':
                return imagecreatefrompng($filename);
                break;
            case 'image/gif':
                return imagecreatefromgif($filename);
                break;
            case 'image/bmp':
            case 'image/wbmp':
                return imagecreatefromwbmp($filename);
                break;
        }
    }
}
